package com.zzyl.nursing.controller.member;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zzyl.common.annotation.Log;
import com.zzyl.common.core.controller.BaseController;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.enums.BusinessType;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.ThreadLocalUtil;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.service.IReservationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 预约Controller
 * 
 * @author zzyl
 */
@Api(tags = "预约管理")
@RestController
public class ReservationController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ReservationController.class);
    
    @Autowired
    private IReservationService reservationService;

    /**
     * 查询当天取消预约数量
     */
    @ApiOperation("查询当天取消预约数量")
    @GetMapping({"/member/reservation/cancelled-count", "/reservation/cancelled-count"})
    public AjaxResult getCancelledCount()
    {
        try {
            Long userId = ThreadLocalUtil.get();
            if (userId == null) {
                log.error("用户ID为空，无法查询取消预约数量");
                return AjaxResult.success("查询成功", 0);
            }
            int count = reservationService.selectCancelledCount();
            log.info("查询取消预约数量成功，用户ID：{}，数量：{}", userId, count);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            log.error("查询取消预约数量失败", e);
            return AjaxResult.error("查询失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 查询每个时间段剩余预约次数
     */
    @ApiOperation("查询每个时间段剩余预约次数")
    @GetMapping({"/member/reservation/countByTime", "/reservation/countByTime"})
    public AjaxResult getCountByTime(@RequestParam Long time)
    {
        try {
            log.info("查询时间段剩余预约次数，时间：{}", time);
            List<Map<String, Object>> list = reservationService.selectCountByTime(time);
            log.info("查询时间段剩余预约次数成功，结果数量：{}", list.size());
            return AjaxResult.success("查询成功", list);
        } catch (Exception e) {
            log.error("查询时间段剩余预约次数失败", e);
            return AjaxResult.error("查询失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 新增预约
     */
    @ApiOperation("新增预约")
    @Log(title = "预约管理", businessType = BusinessType.INSERT)
    @PostMapping({"/member/reservation", "/reservation"})
    public AjaxResult add(@Validated @RequestBody Reservation reservation)
    {
        try {
            log.info("=== 新增预约接口开始 ===");
            log.info("收到预约请求：{}", reservation);
            
            // 检查用户ID
            Long userId = ThreadLocalUtil.get();
            log.info("当前用户ID：{}", userId);
            if (userId == null) {
                log.error("用户ID为空，无法进行预约");
                return AjaxResult.error("用户未登录，请重新登录");
            }
            
            // 设置创建者
            reservation.setCreateBy(String.valueOf(userId));
            
            // 检查当天取消预约次数是否超过3次
            int cancelledCount = reservationService.selectCancelledCount();
            log.info("当天取消预约次数：{}", cancelledCount);
            if (cancelledCount >= 3) {
                return AjaxResult.error("当天取消预约次数已达上限，无法再次预约");
            }
            
            // 设置默认状态为待确认
            reservation.setStatus(0);
            log.info("准备插入预约数据：{}", reservation);
            int result = reservationService.insertReservation(reservation);
            log.info("插入预约结果：{}", result);
            if (result > 0) {
                log.info("=== 新增预约接口成功 ===");
                return AjaxResult.success("预约成功");
            } else {
                log.error("=== 新增预约接口失败：数据库插入失败 ===");
                return AjaxResult.error("预约失败，请重试");
            }
        } catch (Exception e) {
            log.error("=== 新增预约接口异常 ===", e);
            return AjaxResult.error("预约失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 分页查询预约
     */
    @ApiOperation("分页查询预约")
    @GetMapping({"/member/reservation/page", "/reservation/page"})
    public AjaxResult page(Reservation reservation)
    {
        try {
            log.info("=== 分页查询预约开始 ===");
            startPage();
            // 只查询当前用户的预约
            Long userId = ThreadLocalUtil.get();
            log.info("从ThreadLocal获取的用户ID：{}", userId);
            if (userId == null) {
                log.error("用户ID为空，无法查询预约");
                Map<String, Object> emptyResult = new HashMap<>();
                emptyResult.put("rows", new ArrayList<>());
                emptyResult.put("total", 0);
                return AjaxResult.success("查询成功", emptyResult);
            }
            reservation.setCreateBy(String.valueOf(userId));
            log.info("设置查询条件createBy：{}", reservation.getCreateBy());
            List<Reservation> list = reservationService.selectReservationList(reservation);
            log.info("查询预约列表成功，用户ID：{}，结果数量：{}", userId, list.size());
            if (!list.isEmpty()) {
                log.info("第一条记录的createBy：{}", list.get(0).getCreateBy());
            }
            
            // 构建分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("rows", list);
            result.put("total", list.size()); // 这里应该使用实际的总数，但为了兼容性先使用list.size()
            
            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            log.error("查询预约列表失败", e);
            return AjaxResult.error("查询失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 取消预约
     */
    @ApiOperation("取消预约")
    @Log(title = "预约管理", businessType = BusinessType.UPDATE)
    @PutMapping({"/member/reservation/{id}/cancel", "/reservation/{id}/cancel"})
    public AjaxResult cancel(@PathVariable Long id)
    {
        try {
            // 检查是否是当前用户的预约
            Reservation reservation = reservationService.selectReservationById(id);
            if (reservation == null) {
                return AjaxResult.error("预约不存在");
            }
            Long userId = ThreadLocalUtil.get();
            if (userId == null || !reservation.getCreateBy().equals(String.valueOf(userId))) {
                return AjaxResult.error("无权限操作此预约");
            }
            
            int result = reservationService.cancelReservation(id);
            if (result > 0) {
                return AjaxResult.success("取消预约成功");
            } else {
                return AjaxResult.error("取消预约失败，请重试");
            }
        } catch (Exception e) {
            log.error("取消预约失败", e);
            return AjaxResult.error("取消预约失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 完成预约（后台核销）
     */
    @ApiOperation("完成预约")
    @Log(title = "预约管理", businessType = BusinessType.UPDATE)
    @PutMapping({"/member/reservation/{id}/complete", "/reservation/{id}/complete"})
    public AjaxResult complete(@PathVariable Long id)
    {
        try {
            // 检查是否是当前用户的预约
            Reservation reservation = reservationService.selectReservationById(id);
            if (reservation == null) {
                return AjaxResult.error("预约不存在");
            }
            Long userId = ThreadLocalUtil.get();
            if (userId == null || !reservation.getCreateBy().equals(String.valueOf(userId))) {
                return AjaxResult.error("无权限操作此预约");
            }
            
            int result = reservationService.completeReservation(id);
            if (result > 0) {
                return AjaxResult.success("核销成功");
            } else {
                return AjaxResult.error("核销失败，请重试");
            }
        } catch (Exception e) {
            log.error("完成预约失败", e);
            return AjaxResult.error("核销失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 获取预约详细信息
     */
    @ApiOperation("获取预约详细信息")
    @GetMapping(value = {"/member/reservation/{id}", "/reservation/{id}"})
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        try {
            Reservation reservation = reservationService.selectReservationById(id);
            if (reservation == null) {
                return AjaxResult.error("预约不存在");
            }
            Long userId = ThreadLocalUtil.get();
            if (userId == null || !reservation.getCreateBy().equals(String.valueOf(userId))) {
                return AjaxResult.error("无权限查看此预约");
            }
            return AjaxResult.success("查询成功", reservation);
        } catch (Exception e) {
            log.error("获取预约详情失败", e);
            return AjaxResult.error("获取预约详情失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 修改预约
     */
    @ApiOperation("修改预约")
    @Log(title = "预约管理", businessType = BusinessType.UPDATE)
    @PutMapping({"/member/reservation", "/reservation"})
    public AjaxResult edit(@Validated @RequestBody Reservation reservation)
    {
        try {
            // 检查是否是当前用户的预约
            Reservation existingReservation = reservationService.selectReservationById(reservation.getId());
            if (existingReservation == null) {
                return AjaxResult.error("预约不存在");
            }
            Long userId = ThreadLocalUtil.get();
            if (userId == null || !existingReservation.getCreateBy().equals(String.valueOf(userId))) {
                return AjaxResult.error("无权限操作此预约");
            }
            
            int result = reservationService.updateReservation(reservation);
            if (result > 0) {
                return AjaxResult.success("修改预约成功");
            } else {
                return AjaxResult.error("修改预约失败，请重试");
            }
        } catch (Exception e) {
            log.error("修改预约失败", e);
            return AjaxResult.error("修改预约失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }

    /**
     * 删除预约
     */
    @ApiOperation("删除预约")
    @Log(title = "预约管理", businessType = BusinessType.DELETE)
    @DeleteMapping({"/member/reservation/{ids}", "/reservation/{ids}"})
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        try {
            // 检查是否是当前用户的预约
            Long userId = ThreadLocalUtil.get();
            for (Long id : ids) {
                Reservation reservation = reservationService.selectReservationById(id);
                if (reservation == null) {
                    return AjaxResult.error("预约不存在");
                }
                if (userId == null || !reservation.getCreateBy().equals(String.valueOf(userId))) {
                    return AjaxResult.error("无权限操作此预约");
                }
            }
            
            int result = reservationService.deleteReservationByIds(ids);
            if (result > 0) {
                return AjaxResult.success("删除预约成功");
            } else {
                return AjaxResult.error("删除预约失败，请重试");
            }
        } catch (Exception e) {
            log.error("删除预约失败", e);
            return AjaxResult.error("删除预约失败：" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
        }
    }
} 